#include "mainwidget.h"

#include <QDebug>

MainWidget::MainWidget(QWidget *parent) : QWidget(parent)
{
    slotSetRowCol(10, 10); // 初始化
}

QString MainWidget::exportText(int row, int col)
{
    int index = 0; // 按钮数组索引
    QString text = "{\n";

    for (int i = 0; i < row; i++) {
        text += "    { ";
        for (int j = 0; j < col; j++) {

            // 添加元素间逗号
            if (j != 0) {
                text += ", ";
            }

            text += buttons[index++]->isChecked() ? "1" : "0";
        }

        if (i == row - 1) {
            text += " }\n";
        } else {
            text += " },\n";
        }
    }

    text += "}";

    return text;
}

void MainWidget::setReverse(MainWidget::Reverse reverse)
{
    switch (reverse) {
    case OUT_REVERSE: {
        int index = 0; // 按钮数组当前元素的下标
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                QPushButton* btn = buttons[index];

                // 取反外围
                if (i == 0 || j == 0 || i == row - 1 || j == col - 1) {
                    btn->setChecked(!btn->isChecked());
                }

                index++;
            }
        }
        break;}
    case ALL_REVERSE: {
        int index = 0; // 按钮数组当前元素的下标
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                QPushButton* btn = buttons[index];

                // 取反全部
                btn->setChecked(!btn->isChecked());

                index++;
            }
        }
        break;}
    default:
        break;
    }
}

void MainWidget::slotSetRowCol(int row, int col)
{
    this->row = row;
    this->col = col;

    // 清除原主窗口布局
    delete this->layout();

    // 重新创建新窗口布局
    QGridLayout* layout = new QGridLayout(this);
    layout->setSpacing(0);

    // 判断按钮是否足够
    if (buttons.size() < row * col) {
        // 新增到足量的button
        for (int k = buttons.size(); k <row * col;k++) {
            QPushButton* btn = new QPushButton();
            btn->setCheckable(true);
            buttons.append(btn);
        }
    } else if (buttons.size() > row * col) {
        // 移除多余的button
        for (int k = buttons.size() - 1; k >= row * col; k--) {
            QPushButton* btn = buttons.at(k);
            delete btn;
            buttons.pop_back();
        }
    }

    qDebug() << buttons.size() << row * col;

    int index = 0; // 按钮数组当前元素的下标
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            QPushButton* btn = buttons[index];
            btn->setChecked(false);

            // 添加按钮到界面
            layout->addWidget(btn, i, j);

            index++;
        }
    }

    this->setLayout(layout);
}
